<?php

/**
 * File: control.php
 * Author: Sinisa Vidic [Team Six]
 * Created: December 3, 2012
 * Description: the "brain" of the application, responsible for controlling how
 * a dynamic page is assembled, based on user input passed on through $_POST.
 */
require_once("storage.php");
require_once("view.php");
require_once("util.php");

/**
 * Controls the entire execution of the application.
 */
function main()
{
    $out = "";
    $errorMsg = "";
	
	
    $errorMsg = processInsertForm();
    showNewForm();
	processDeleteForm();
	showErrorMessage($errorMsg);
   showInternshipListing($out);
   
	$order = "sponsorName";
	
	$orderAllowed = array('sponsorName', 'sponsorCity', 'sponsorState', 'postingDate', 'internshipTitle',
	                      'internshipCategory', 'isPaid'); 
	if (isset($_GET['sortBy']) && in_array($_GET['sortBy'], $orderAllowed))
    {
      $order = $_GET['sortBy'];
    }
    $out = makeInternshipListing($order);
	print_r($order);
	
     
}




function processDeleteForm( ) 
{
  if(isset($_POST['deleteButton']))
  {
	$deleteID = $_POST['deleteID'];
	deleteInternship($deleteID);
  }
}

/**
 * Retrieves input data from $_POST and calls insertInternship( ) to insert
 * a record in the internship table. Calls validateInternshipData( ) with input
 * data that has to be checked for correctness. If input data is not valid, 
 * an error message is assigned to a local variable $errorMsg. 
 * @return empty string if all values are entered, or the string in $errorMsg.
 */
 
function processInsertForm()
{
    $errorMsg = "";
    $sponsorName = "";
    $sponsorCity = "";
    $sponsorState = "";
    $postingDate = "";
    $internshipTitle = "";
    $internshipCategory = "";
    $isPaid = "";

  //  debug("\$_POST", $_POST); //Post Debug 
  //	debug("\$_GET", $_GET); //Get Debug
    if (!isset($_POST['submitButton']))
	{
        showWelcome();
    }
	else
	{
        $sponsorName = $_POST['sponsorName'];
        $sponsorCity = $_POST['sponsorCity'];
        $sponsorState = $_POST['sponsorState'];
        $postingDate = $_POST['postingDate'];
        $internshipTitle = $_POST['internshipTitle'];
        $internshipCategory = $_POST['internshipCategory'];
        $isPaid = $_POST['isPaid'];

        $errorMsg = validateInternshipData($sponsorName, $sponsorCity, $sponsorState, $postingDate, 
										   $internshipTitle, $internshipCategory, $isPaid);
        if ($errorMsg == "")
		{
            //insert function from storage.php
            insertInternship($sponsorName, $sponsorCity, $sponsorState, $postingDate, $internshipTitle, 
							 $internshipCategory, $isPaid);
        }
    }
    return $errorMsg;
}

/**
 * Checks validity of parameters.
 * [complete this block comment with @param tags as appropriate]

 * @param string $sponsorName what the user entered for the sponsor name
 * @param string $sponsorCity what the user entered for the spnosor city
 * @param string $sponsorState what the user entered for the sponsor state
 * @param string $postingDate what the user entered for the posting date
 * @param string $internshipTitle what the user entered for the internship title
 * @param string $internshipCategory what the user entered for the internship category
 * @param string $isPaid what the user entered for the is paid
 * @return string error message if any of the parameters has invalid data.
 */
function validateInternshipData($sponsorName, $sponsorCity, $sponsorState, $postingDate, 
                                $internshipTitle, $internshipCategory, $isPaid)
{
    $errorMsg = "";

    if ($sponsorName == "" || $sponsorCity = "" || $sponsorState = "" || $postingDate == "" || $internshipTitle = "" || 
	    $internshipCategory == "" || $isPaid = "")
	{
        $errorMsg = "All fields are required!";
    }
    if (!((preg_match('/[A-Za-z]+/', $sponsorName)) ||
            (preg_match('/[A-Za-z]+/', $sponsorCity)) ||
            (preg_match('/[A-Za-z]+/', $sponsorState)) ||
            (preg_match('/[A-Za-z]+/', $internshipTitle)) ||
            (preg_match('/[A-Za-z]+/', $internshipCategory))))
	{
        $errorMsg = $errorMsg . " Only letters allowed";
    }
    // Date format YYYY/MM/DD
    if (preg_match("/([0-9]{4})\/([0-9]{2})\/([0-9]{2})/", $postingDate, $matches))
	{
        // uses checkdate() function to check if the date input is correct date
        if (checkdate($matches[2], $matches[3], $matches[1]))
		{
				// Correct date nothing to be done here
        } 
		else
		{
            $errorMsg = $errorMsg . "Wrong date. Try Again!";
        }
    }
	else
	{
        $errorMsg = $errorMsg . "Wrong date format. Date format allowed YYYY/MM/DD.";
    }

    return $errorMsg;
}

/**
 * Gets all internship records by calling selectAllInternships( ) in storage.php.
 * Creates listing by using a loop in which it calls showOneListing( ) in 
 * view.php. 
 * @return string with formatted listing of all internsihp records.
 */
function makeInternshipListing($order)
{
    $out = "";
    $oneInternship = array();
    $internships = array();
    

    $internships = selectSortedInternships($order);
    $i = 0;
    foreach ($internships as $oneInternship)
	{
        $i++;
        $out = $out . showOneListing($i, $oneInternship['internshipID'], $oneInternship['sponsorName'], $oneInternship['sponsorCity'], 
										 $oneInternship['sponsorState'], $oneInternship['postingDate'], 
										 $oneInternship['internshipTitle'], $oneInternship['internshipCategory'], 
										 $oneInternship['isPaid']);
    }
	return $out;
}

?>